import os
import log
import ConfigParser

PNGGUANT = "pngquant/pngquant"


def _compress_png(_file_full_path):
    arg = os.path.abspath('.') + os.sep + PNGGUANT
    arg += " --force"
    arg += " --ordered"
    arg += " --output " + _file_full_path
    arg += " --speed=11"
    arg += " --quality=0-100"
    arg += " " + _file_full_path
    os.system(arg)
    log.debug("compre image : " + _file_full_path)


def find_png(_dir):
    cf = ConfigParser.ConfigParser()
    cf.read("../conf/project.conf")
    try:
        SHIELD_FILE_LIST = cf.get("resource", "shield_file_list").split(",")
    except ConfigParser.NoOptionError, e:
        print e
    else:
        for _file in os.listdir(_dir):
            if os.path.isdir(_dir + os.sep + _file):
                find_png(_dir + os.sep + _file)
            else:
                name = _file.split(".")
                if name[1] == "png" or name[1] == "jpg":
                    _is_shield = False
                    for shield_file in SHIELD_FILE_LIST:
                        if shield_file == name[0]:
                            _is_shield = True
                            break
                    if not _is_shield:
                        _file_full_path = _dir + os.sep + _file
                        _compress_png(_file_full_path)
